package com.sirdc.modules.sys.web.Accraditation;

import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.Project.util.MessageUtil;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.databean.BnpUserDatabean;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.entity.Message;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/accraditation")
public class AccraditationController {
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private NewProjectsService nService;
    @Autowired
    private MessageService ms;
    @Autowired
    private BnpUserService bus;
    @Autowired
    private MessageUtil mu;

    @ModelAttribute("headType")
    public String returnHeadType() {
        return "节点审核模块";
    }

    /**
     * 确认节点列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/go/projectslist", method = RequestMethod.GET)
    public String goProjectsList(HttpServletRequest request, Model model) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        model.addAttribute("leftType", "确认节点列表");
        double page = nService.getProjectSumPage(null);
        model.addAttribute("totalPage", page);
        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);
        //待办任务个数
        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        model.addAttribute("nodeCount", nodeCount);
        int myTackTaskNum = (int) WebUtils.getSessionAttribute(request, "myTackTaskNum");
        model.addAttribute("myTackTaskNum", myTackTaskNum);
        return "/modules/Accraditation/Accraditation_project";
    }

    /**
     * 获取项目数据
     *
     * @param filter
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getProjectslist", method = RequestMethod.GET)
    public Object getProjectslist(@ModelAttribute NewProjectsFilter filter, Model model, HttpServletRequest request) {
        BnpUser bu = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bu)) {
            return "/modules/login/login";
        }
        filter.setCurrentPage(filter.getPage());
//        List<NewProjects> list = nService.getProjectInfo(filter);
        NodeNewschedulesFilter nodeNewschedulesFilter = new NodeNewschedulesFilter();
        Paging paging = new Paging();
        paging.setCurrentPage(filter.getPage());
        nodeNewschedulesFilter.setPaging(paging);
        /*
        nodeNewschedulesFilter.setResDept(bu.getBranch());
        nodeNewschedulesFilter.setOperatorUser(bu.getName());
        */
        nodeNewschedulesFilter.setOperatorPhone(bu.getPhone());
        //搜索责任单位
        if(StringUtils.isNotBlank(filter.getResDept())){
            nodeNewschedulesFilter.setResDept_th(true);
            //搜索条件:责任单位
            nodeNewschedulesFilter.setType(filter.getResDept());
        }else{
            nodeNewschedulesFilter.setResDept_th(false);
        }
        //搜索项目状态
        if(StringUtils.isNotBlank(filter.getStatus())){
            nodeNewschedulesFilter.setStatus(filter.getStatus());
        }
        //搜索项目名称
        if(StringUtils.isNotBlank(filter.getName())){
            nodeNewschedulesFilter.setProjectName(filter.getName());
        }
        List<NewProjects> list = nodeNewschedulesService.queryProjectByAccraditation(nodeNewschedulesFilter);
        int totalPage = nodeNewschedulesFilter.getPaging().getPageCount();
        //前端需要加序号
        int serialNumber = (filter.getPage() - 1) * 10 + 1;
        for (NewProjects projects : list) {
            //前端编号（客户需要添加）
            projects.setUpdUser(serialNumber + "");
            serialNumber++;
        }
        //查找相应审批部门的节点(所有节点包含大小节点，没有判断确定与否)
        List<NodeNewschedules> allStateNullList = nodeNewschedulesService.getByResDeptAndOperatorUser(null, bu.getBranch(), bu.getName(), "");
        //该用户不负责审批，所以查到的数据为0
        if (allStateNullList.size() == 0) {
            Map<String, Object> map = new HashMap<>();
            System.out.println("totalPage" + totalPage);
            map.put("totalPage", totalPage);
            map.put("model", list);
            return map;
        }//查找相应审批部门的节点(所有节点包含大小节点，有判断确定与否)
        List<NodeNewschedules> allState1List = nodeNewschedulesService.getByResDeptAndOperatorUser(null, bu.getBranch(), bu.getName(), "1");
        Map<String, List<NodeNewschedules>> map1 = new HashMap<>();
        Map<String, List<NodeNewschedules>> map2 = new HashMap<>();
        for (NewProjects project : list) {
            List<NodeNewschedules> nullStateList = new ArrayList<>();
            List<NodeNewschedules> stateList = new ArrayList<>();
            for (NodeNewschedules nullState : allStateNullList) {
                if (project.getSysId().equals(nullState.getProjectId())) {
                    nullStateList.add(nullState);
                }
            }
            map1.put(project.getSysId(), nullStateList);
            for (NodeNewschedules state : allState1List) {
                if (project.getSysId().equals(state.getProjectId())) {
                    stateList.add(state);
                }
            }
            map2.put(project.getSysId(), stateList);
        }
        List<NewProjects> lists = new ArrayList<>();
        for (NewProjects np : list) {
            String status = "0";
            List<NodeNewschedules> list1 = map1.get(np.getSysId()); //未确定的节点
            List<NodeNewschedules> list2 = map2.get(np.getSysId()); //已确定的节点
            if (list1.size() == list2.size()) {
                status = "2";               //所有节点都确认完毕
            } else {
                if (list2.size() == 0 ) {
                    status = "0";           //所有节点未确认
                }else{
                    status = "1";           //部分节点未确认
                }
            }
            /*else if (list1.size() == list2.size()) {
                status = "2";
            }*/
            np.setStatus(status);
            if (status.equals(filter.getState())) {
                lists.add(np);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("totalPage", totalPage);
        map.put("model", list);
        return map;
    }

    /**
     * 跳转到项目详细
     *
     * @param request
     * @param model
     * @param filter
     * @return
     */
    @RequestMapping(value = "/go/configNode", method = RequestMethod.GET)
    public String goConfigNode(HttpServletRequest request, Model model, NewProjectsFilter filter) {
        model.addAttribute("leftType", "确认节点列表");
        NewProjects mP = nService.getById(filter.getSysId());
        model.addAttribute("newProjects", mP);
        List<Map<String, Object>> List1 = new ArrayList<>();
        BnpUser bu = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bu)) {
            return "/modules/login/login";
        }
        List<NodeNewschedules> list_a = nodeNewschedulesService.queryListByProjectId(filter.getSysId(), "1", bu.getBranch(), "", bu.getName());
//        List<NodeNewschedules> list_b = nodeNewschedulesService.queryListByProjectId(filter.getSysId(), "2", bu.getBranch(), "", bu.getName());
        List<String> bigNode = new ArrayList<>();
        List<NodeNewschedules> smallNode = new ArrayList<>();
        for (NodeNewschedules nns : list_a) {
            List<NodeNewschedules> childNodesList = new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            //大节点
            if ("0".equals(nns.getNodeIds())) {
                bigNode.add(nns.getNodeId());
                map1.put("sysId", nns.getSysId());
                map1.put("idFlag", nns.getSysId().hashCode());
                map1.put("nodeId", nns.getNodeId());
                map1.put("preNodeId", nns.getPreNodeId());
                map1.put("nodeName", nns.getNodeName());
                map1.put("resDept", nns.getResDept());
                map1.put("resUser", nns.getResUser());
                map1.put("nodeType", nns.getNodeType());
                map1.put("status", nns.getStatus());
                map1.put("state", nns.getState());
                for (NodeNewschedules nns2 : list_a) {
                    //小节点
                    if (!"0".equals(nns2.getNodeIds())) {
                        String[] nodeid = nns2.getNodeId().split("\\.");
                        if (nodeid[0].equals(nns.getNodeId())) {
                            if (ObjectUtils.isBlank(nns2.getResUser())) {
                                nns2.setResUser("0");
                            }
                            if (ObjectUtils.isBlank(nns2.getOperatorUser())) {
                                nns2.setOperatorUser("0");
                            }
                            childNodesList.add(nns2);
                        } else {
                            smallNode.add(nns2);
                        }
                    }
                }
                map1.put("childNodesList", childNodesList);
                List1.add(map1);
            }
        }
        //处理小节点
        for (NodeNewschedules nns : smallNode) {
            if (!bigNode.contains(nns.getNodeIds())) {
                List<NodeNewschedules> childNodesList = new ArrayList<>();
                Map<String, Object> map2 = new HashMap<>();
                map2.put("sysId", nns.getSysId());
                map2.put("idFlag", nns.getSysId().hashCode());
                map2.put("nodeId", nns.getNodeId());
                map2.put("preNodeId", nns.getPreNodeId());
                map2.put("nodeName", nns.getNodeName());
                map2.put("resDept", nns.getResDept());
                map2.put("resUser", nns.getResUser());
                map2.put("nodeType", nns.getNodeType());
                map2.put("status", nns.getStatus());
                map2.put("state", nns.getState());
                childNodesList.add(nns);
                map2.put("childNodesList", childNodesList);
                List1.add(map2);
            }
        }
        BnpUserFilter filters = new BnpUserFilter();
        filters.setRole("责任人");

        filters.setBranch(bu.getBranch());
        List<BnpUser> dutyList = bus.getUserInfo(filters);
        filters.setRole("经办人");
        List<BnpUser> handleList = bus.getUserInfo(filters);
        model.addAttribute("dutyList", dutyList);
        model.addAttribute("handleList", handleList);
        model.addAttribute("nodesList", List1);
        return "/modules/Accraditation/configNode";
    }

    /**
     * 小节点确定操作
     *
     * @param request
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/configNode", method = RequestMethod.POST)
    public Object configNode(HttpServletRequest request, Model model) {
        model.addAttribute("leftType", "我的项目");
        Map<String, Object> map = new HashMap<String, Object>();
        String projectId = request.getParameter("projectId");
        String planTime = request.getParameter("planTime");
        String nodeId = request.getParameter("nodeId");
        NodeNewschedules ns = nodeNewschedulesService.getNodeNewschedulesByProjectIdAndNodeId(projectId, nodeId);
        ns.setPlanTime(planTime);
        ns.setState("1");
        nodeNewschedulesService.update(ns);
        List<NodeNewschedules> list = nodeNewschedulesService.getNodePlanTime(projectId, "1");
        if (list.size() == 0) {
            NewProjects np = nService.getById(projectId);
            np.setStatus("1");
            nService.update(np);
            BnpUser bnpUser = bus.getById(np.getUserId());
            Map<String, Object> ma = mu.confirmTaskMessage(bnpUser.getName(), bnpUser.getPhone(), "《" + np.getName() + "》", "业主备件与第三方编制");
            if ("0".equals(ma.get("code").toString())) {
                Message m = new Message();
                m.setRecipients("np.getContactName()");
                m.setText(ma.get("text").toString());
                m.setType("0");
                m.setPhone(np.getContactPhone());
                m.setMsg(ma.get("msg").toString());
                m.setProjectName(np.getName());
                m.setResDept("业主单位");
                ms.save(m);
            }
        }
        map.put("msp", "提交成功！");
        map.put("status", true);
        return map;
    }

    /**
     * 大节点确定操作
     *
     * @param request
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/configBigNode", method = RequestMethod.POST)
    public Object configBigNode(HttpServletRequest request, Model model) {
        model.addAttribute("leftType", "我的项目");
        Map<String, Object> map = new HashMap<>();
        String projectId = request.getParameter("projectId");
        String state = request.getParameter("state");
        String nodeId = request.getParameter("nodeId");
        NodeNewschedules ns = nodeNewschedulesService.getNodeNewschedulesByProjectIdAndNodeId(projectId, nodeId);
        ns.setState(state);
        nodeNewschedulesService.update(ns);
        if ("2".equals(state)) {
            List<NodeNewschedules> lists = nodeNewschedulesService.getNodeIdsLists(nodeId, projectId);
            for (NodeNewschedules nos : lists) {
                nos.setState("2");
                nodeNewschedulesService.update(nos);
            }
        }
        if ("1".equals(state)) {
            List<NodeNewschedules> lists = nodeNewschedulesService.getNodeIdsLists(nodeId, projectId);
            for (NodeNewschedules nos : lists) {
                nos.setState("1");
                nodeNewschedulesService.update(nos);
            }
        }
        List<NodeNewschedules> list = nodeNewschedulesService.queryNoStateNode(projectId);
        if (list.size() == 0) {
            //刷新节点流程
            List<String> sysIds = new ArrayList<>();
            sysIds.add(projectId);
            nService.updateNodeProcess(sysIds);
            NewProjectsFilter filter = new NewProjectsFilter();
            filter.setSysId(projectId);
            nService.initPassProject(filter);
        }
        map.put("msp", "提交成功！");
        map.put("status", true);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/updateBigNodeFinishTime", method = RequestMethod.POST)
    public Object updateBigNodeFinishTime(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String projectId = request.getParameter("projectId");       //项目Id
        String nodeId = request.getParameter("nodeId");             //大节点Id
        //获取大节点
        NodeNewschedules bigNode = nodeNewschedulesService.getNnsByProjectIdAndNodeId(projectId, nodeId);

        List<NodeNewschedules> nodeList = nodeNewschedulesService.getNodeByProjectId(projectId);
        List<NodeNewschedules> nodes = new ArrayList<>();
        List<NodeNewschedules> nodesHaveFts = new ArrayList<>();
        for (NodeNewschedules node : nodeList) {
            if (nodeId.equals(node.getNodeIds())) {
                nodes.add(node);
            }
        }
        //判断大节点下小节点是否全部完成
        //默认完成为：1
        boolean isFinished = true;
        for (NodeNewschedules n : nodes) {
            if (!"2".equals(n.getStatus())) {
                isFinished = false;         //未完成
                break;
            } else {
                if (StringUtils.isNotBlank(n.getFactFinishDate())) {
                    nodesHaveFts.add(n);
                }
            }
        }

        //全部完成进行时间排序
        if (isFinished && nodesHaveFts.size() > 0) {
            Collections.sort(nodesHaveFts, new Comparator<NodeNewschedules>() {
                public int compare(NodeNewschedules p1, NodeNewschedules p2) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                    int result = 0;
                    if (p1.getFactFinishDate().equals(p2.getFactFinishDate())) {
                        return result;
                    }
                    try {
                        Date date1Str = format.parse(p1.getFactFinishDate());
                        Date date2Str = format.parse(p2.getFactFinishDate());
                        if (date1Str.after(date2Str)) {
                            result = -1;
                        } else {
                            result = 1;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    return result;


                }
            });
            String factFinishTime = nodesHaveFts.get(0).getFactFinishDate();
            bigNode.setFactFinishDate(factFinishTime);
            nodeNewschedulesService.update(bigNode);
            map.put("ft", factFinishTime);
            map.put("msg", "更新成功！");
            map.put("res", true);
        } else {

            map.put("msg", "暂无实际结束时间");
            map.put("res", false);
        }
        return map;
    }
}
